package slu.appli.android.wodtimera;

import slu.appli.logger.interfaces.LoggerInterface;
import slu.appli.sound.interfaces.SoundPlayerInterface;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class SoundPlayer
implements SoundPlayerInterface {
	public static final String RES_DEFAULT_BEEP = "Default";
	
	private final SoundPool soundPool;
	private final Context context;
	private LoggerInterface logger = null;
	private int soundIndex = -1;
	
	private float leftVolume = 10.0f;
	private float rightVolume = 10.0f;
	private float rate = 1.0f;
	
	public SoundPlayer(Context context,
			LoggerInterface logger) {
		super();
		this.logger = logger;
		this.context = context;
		this.soundPool = this.buildSoundPool();
		this.setFile(SoundPlayer.RES_DEFAULT_BEEP);
	}
	
	private SoundPool buildSoundPool() {
		SoundPool sp = null;
		try {
			sp = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 0);
		}
		catch (Exception e) {
			sp = null;
			this.logger.addException(e);
		}
		return sp;
	}

	public float getLeftVolume() {
		return leftVolume;
	}

	public void setLeftVolume(float leftVolume) {
		this.leftVolume = leftVolume;
	}

	public float getRightVolume() {
		return rightVolume;
	}

	public void setRightVolume(float rightVolume) {
		this.rightVolume = rightVolume;
	}

	public float getRate() {
		return rate;
	}

	public void setRate(float rate) {
		this.rate = rate;
	}

	public Context getContext() {
		return context;
	}

	@Override
	public void close() {
		try {
			this.soundPool.release();
		} catch (Exception e) {
			if (this.logger != null) this.logger.addException(e);
		}
	}
	
	public LoggerInterface getLogger() {
		return logger;
	}

	@Override
	public void setLogger(LoggerInterface logger) {
		this.logger = logger;
	}

	@Override
	public void setFile(String ressourceName) {
		if (this.soundIndex != -1) {
			this.soundPool.unload(this.soundIndex);
			this.soundIndex = -1;
		}
		try {
			if (SoundPlayer.RES_DEFAULT_BEEP.equals(ressourceName)) {
				this.soundIndex = this.soundPool.load(this.context, R.raw.beep, 1);
			}
			else throw new IndexOutOfBoundsException(ressourceName);
		}
		catch (Exception e){
			if (this.logger != null) this.logger.addException(e);
		}
	}
	
	@Override
	public void play() {
		try{
			this.soundPool.play(
					this.soundIndex,
					this.leftVolume,
					this.rightVolume,
					1, 0,
					this.rate);
		}
		catch (Exception e){
			if (this.logger != null) this.logger.addException(e);
		}
	}

}
